package agh.sr.lab4.chat.client;

import java.io.FileNotFoundException;
import java.io.IOException;

import Chat.AccountAlreadyExistsException;
import Chat.ChatManagerPrx;
import Chat.ChatManagerPrxHelper;
import Chat.ChatRoomPrx;
import Chat.ChatRoomPrxHelper;
import agh.sr.lab4.common.utils.ClientUtils;
import agh.sr.lab4.common.utils.Config;

public class ChatClient {

	private int status = 0;
	private Ice.Communicator ic = null;
	private String serverConnectionString = null;
	private ChatManagerPrx chatManagerPrx = null;

	private String room = "";

	public static void main(String[] args) {
		ChatClient chatClient = new ChatClient();
		try {
			chatClient.init(args);
			chatClient.mainLoop();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void init(String[] args) throws FileNotFoundException, IOException {
		String serverName = "CommonServer.Proxy";
		ic = Ice.Util.initialize(args);
		Ice.ObjectPrx base = ic.propertyToProxy(serverName);

		chatManagerPrx = ChatManagerPrxHelper.checkedCast(base);
		if (chatManagerPrx == null)
			throw new Error("Invalid proxy");

		// extract connection info from properties
		serverConnectionString = new ClientUtils()
				.extractConnectionInfoFromProperty(args, serverName);

		System.out.println("SERVER: " + serverConnectionString);
	}

	private void mainLoop() {
		try {
			String line = null;
			java.io.BufferedReader in = new java.io.BufferedReader(
					new java.io.InputStreamReader(System.in));
			do {
				try {
					printMainLoopOptions();
					System.out.print("==> ");
					System.out.flush();
					line = in.readLine();
					if (line == null) {
						break;
					}
					if (line.equals("c") || line.equals("create")) {
						handleCreateAccount();
					} else if (line.equals("j") || line.equals("join")) {
						handleJoin();
					} else if (line.equals("t") || line.equals("test")) {
						handleTest();
					}
				} catch (Ice.ObjectNotExistException ex) {
					System.err.println("Account NOT exist");
				} catch (java.io.IOException ex) {
					System.err.println(ex);
				}
			} while ((!line.equals("q") && (!line.equals("quit"))));

		} catch (Ice.LocalException e) {
			e.printStackTrace();
			status = 1;
		} catch (Exception e) {
			System.err.println(e.getMessage());
			status = 1;
		}
		if (ic != null) {
			// Clean up
			try {
				ic.destroy();
			} catch (Exception e) {
				System.err.println(e.getMessage());
				status = 1;
			}
		}
		System.exit(status);

	}

	private void handleTest() {

	}

	private void printMainLoopOptions() {
		System.out.println("+++ CHAT MANAGER - Main Menu, not logged +++");
		System.out.println("+++ options: login(l), join(j), quit(q)");
	}

	private void handleCreateAccount() throws IOException,
			AccountAlreadyExistsException {
		String nick = readString();
		chatManagerPrx.createAccount(nick);
		printInfo("Account created: " + nick);
	}

	private void handleJoin() throws IOException {
		room = readString();
		String proxyString = Config.CHAT_CATEGORY + "/" + room
				+ serverConnectionString;
		System.out.println(proxyString);
		Ice.ObjectPrx base = ic.stringToProxy(proxyString);

		// BankAccountPrx bankAccountPrx =
		// BankAccountPrxHelper.checkedCast(base);
		ChatRoomPrx chatRoom = ChatRoomPrxHelper.uncheckedCast(base);
		if (chatRoom == null)
			throw new Error("Invalid proxy");
		chatRoom.join(room, null);
		chatLoop(chatRoom);
	}

	private void chatLoop(ChatRoomPrx chatRoom) {
		// TODO Auto-generated method stub

	}

	private void printInfo(String msg) {
		System.out.println(">>> " + msg);
	}

	private String readString() throws IOException {
		String _pesel = "";
		java.io.BufferedReader in = new java.io.BufferedReader(
				new java.io.InputStreamReader(System.in));
		do {
			System.out.println("Type pesel:");
			_pesel = in.readLine();
		} while (!_pesel.matches("[0-9]{1,11}"));

		return _pesel;
	}

}
